package pl.pawluk.inz.web.aop;

import java.io.Serializable;
import java.util.Locale;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.naming.AuthenticationException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import pl.pawluk.inz.exceptions.VLPException;
import pl.pawluk.inz.web.BaseBean;


/**
 * @author mandp
 */
@Aspect
@Component
public class ExceptionHandlerAOP implements Serializable {
    private static final Log log = LogFactory.getLog(ExceptionHandlerAOP.class);


    @Pointcut("execution(* pl.pawluk.inz.web.*Bean.*(..))")
    public void handle() {
    }


    public ExceptionHandlerAOP() {
        System.out.println(getClass().getName() + " : create");
    }

    @Autowired
    private transient MessageSource msg;


    @Around("pl.pawluk.inz.web.aop.ExceptionHandlerAOP.handle()")
    public Object doHandle(ProceedingJoinPoint pjp) throws Throwable {
        try {
            if (log.isDebugEnabled()) {
                log.debug("Start Around");
            }
            Object o = pjp.proceed();
            if (log.isDebugEnabled()) {
                log.debug("Stop Around");
            }
            return o;
        } catch (VLPException e) {
            BaseBean.handleException(e, msg);
            return null;
        } catch (AuthenticationException e) {
            throw e;
        } catch (Throwable e) {
            BaseBean.handleException(new Exception(e), msg);
            return null;
        }
    }
}
